package com.android.net.callback;

import com.android.net.convert.Convert;
import com.android.net.response.BaseResponse;
import com.google.gson.stream.JsonReader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;


public abstract class BaseCallback<T> extends AbsCallback<T> {

    @Override
    public T convertResponse(Response response) throws Throwable {
        //以下代码是通过泛型解析实际参数,泛型必须传
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        Type type = params[0];
        if (!(type instanceof ParameterizedType)) {
            throw new IllegalStateException("没有填写泛型参数");
        }
        JsonReader jsonReader = new JsonReader(response.body().charStream());
        Type rawType = ((ParameterizedType) type).getRawType();
        if (rawType == BaseResponse.class) {
            BaseResponse baseResponse = Convert.fromJson(jsonReader, type);
            if (baseResponse.code.equals("200000")) {
                response.close();
                return (T) baseResponse;
            } else {
                response.close();
                throw new IllegalStateException(response.message());
            }
        } else {
            response.close();
            throw new IllegalStateException("基类错误无法解析!");
        }
    }
}
